package adminlogservice

import (
	"vpn-management-server/logger"
	"vpn-management-server/src/dao/adminlogdao"
	"vpn-management-server/src/model/adminlogmodel"
)

var ChanAdminLogs chan adminlogmodel.AdminLog

var ch chan int

func init() {
	ChanAdminLogs = make(chan adminlogmodel.AdminLog, 10)
	ch = make(chan int)
}

func AddAdminLogs(ChanAdminLogs chan adminlogmodel.AdminLog) {
	for {
		select {
		case nums := <-ch:
			logger.Logger.Info("writing admin logger to database")
			var adminLogs []*adminlogmodel.AdminLog
			for i := 0; i < nums; i++ {
				adminLog := <-ChanAdminLogs
				adminLogs = append(adminLogs, &(adminLog))
			}
			go writeAdminLogs(adminLogs)
		}
	}
}

func AddAdminLogToChan(ChanAdminLogs chan adminlogmodel.AdminLog, AdminLog adminlogmodel.AdminLog) {
	ChanAdminLogs <- AdminLog
}

func writeAdminLogs(adminLogs []*adminlogmodel.AdminLog) {
	_, err := adminlogdao.AddAdminLogs(adminLogs)
	if err != nil {
		logger.Logger.Error("add admin log fail")
	}
}

func DetectLogChan() {
	if len(ChanAdminLogs) == 10 {
		ch <- 10
	}
}
